<template>
  <div>
    <div v-if="!readonly" style="text-align: right">
      <el-button-group style="margin-right: 12px; margin-bottom: 4px;">
        <el-tooltip content="保存" placement="top" :open-delay="500">
          <el-button type="primary" icon-class="skill" size="mini" @click="saveCatalog">
            <svg-icon icon-class="save" />
          </el-button>
        </el-tooltip>
      </el-button-group>
    </div>
    <el-card shadow="hover">
      <el-form ref="updateCatalog" size="small" class="demo-table-expand" label-width="90px" label-position="left" :model="catalogInfo" :disabled="readonly">
        <el-form-item
          prop="name"
          label="目录名称"
          :rules="{ required: true, message: '目录名称不能为空', trigger: 'blur' }"
        >
          <el-input
            v-model="catalogInfo.name"
            placeholder="请输入目录名称"
          />
        </el-form-item>
      </el-form>
      <div v-if="!readonly">
        <div v-if="type === 1">
          <el-divider content-position="center">测试用例批量编辑</el-divider>
          <el-table border size="mini" :data="caseTableData" row-key="tableRowKey">
            <el-table-column type="index" align="center" width="50px" label="编号" />
            <el-table-column align="center" label="用例编号" width="100px">
              <template v-slot="scope">
                <el-input v-model="scope.row.number" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="用例名称" prop="name">
              <template v-slot="scope">
                <el-input
                  v-if="scope.$index !== caseTableData.length - 1"
                  v-model="scope.row.name"
                />
                <el-input
                  v-if="scope.$index === caseTableData.length - 1"
                  v-model="scope.row.name"
                  @input="newTableRow()"
                />
              </template>
            </el-table-column>
            <el-table-column align="center" label="编写状态" width="110px">
              <template v-slot="scope">
                <el-select v-model="scope.row.editStatus" placeholder="请选择用例编写状态" style="width: 100%">
                  <el-option v-for="item in editStatusOptions" :key="item.value" :label="item.name" :value="item.value" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" label="优先级" width="85px">
              <template v-slot="scope">
                <el-select v-model="scope.row.priority" placeholder="请选择优先级" style="width: 100%">
                  <el-option v-for="item in priorityOptions" :key="item.value" :label="item.name" :value="item.value" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="before" label="前提条件" align="center">
              <template v-slot="scope">
                <el-input
                  v-model="scope.row.before"
                />
              </template>
            </el-table-column>
            <el-table-column prop="operatingSteps" label="操作步骤" align="center">
              <template v-slot="scope">
                <el-input
                  v-model="scope.row.steps[0].extra1"
                  type="textarea"
                  autosize
                />
              </template>
            </el-table-column>
            <el-table-column prop="except" label="预期结果" align="center">
              <template v-slot="scope">
                <el-input
                  v-model="scope.row.steps[0].extra2"
                  type="textarea"
                  autosize
                />
              </template>
            </el-table-column>
            <el-table-column v-if="!readonly" align="center" label="操作" width="50">
              <template v-slot="scope">
                <el-tooltip v-if="scope.$index !== caseTableData.length - 1" :tabindex="-1" content="删除" placement="top" :open-delay="500">
                  <el-button type="text" @click="delTableRow(scope.$index)">
                    <span class="icon-wrapper"><i class="el-icon-close icon-style" /></span>
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <br>
      </div>
    </el-card>
  </div>
</template>

<script>
import { create, update, selectById as catalogSelectById } from '@/api/functional_test/catalog'
import { del, selectByCatalogId } from '@/api/functional_test/test_case_manage/test_case'
import { saveOrUpdateBatch } from '@/api/functional_test/test_case_manage/test_case'
import { editStatusOptions } from '@/enum/editStatus.js'
import { priorityOptions } from '@/enum/priority.js'

export default {
  components: { },
  props: {
    type: {
      type: Number,
      default: null
    },
    readonly: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      editStatusOptions, // 编写状态 options
      priorityOptions, // 优先级 options
      catalogInfo: {},
      caseTableData: [],
      currentCatalogId: 0, // 当前选中的 tree 的 catalogId
      node_had: undefined, // tree 的根节点
      resolve_had: undefined, // tree 的根节点的 resolve
      activeName: null, // 当前激活的 tab 名称
      element: {}, // element 对象
      currentNode: null, // 当前选中的 tree 节点
      props: { // tree 的 props 对象，用来映射新的 tree 属性
        label: 'name',
        children: '',
        isLeaf: 'leaf',
        key: 'id'
      },
      addNewNode: false // 添加新节点 - 标记
    }
  },
  watch: {
  },
  created() {
  },
  methods: {
    // 装载数据
    loadData(id) {
      // 装载分类数据
      catalogSelectById(id).then(response => {
        this.catalogInfo = response.data
      })

      // 加载分类下所有用例数据
      if (!this.readonly) {
        selectByCatalogId(this.$store.getters.projectId, id).then(res => {
          this.caseTableData = res.data
          this.newTableRow()
        })
      }
    },
    // 点击新增用例按钮时调用此方法
    add(parent_id) {
      this.catalogInfo = {
        parentId: parent_id
      }
      if (!this.readonly) {
        this.caseTableData = []
        this.newTableRow()
      }
    },
    // 删除 测试用例批量编辑 中的一行数据
    delTableRow(index) {
      this.$confirm('是否确认删除当前用例?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.caseTableData[index].id !== 0 && this.caseTableData[index].id !== undefined) {
          del(this.caseTableData[index].id).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.caseTableData.splice(index, 1)
          })
        } else {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.caseTableData.splice(index, 1)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    newTableRow() {
      this.caseTableData.push({
        projectId: this.$store.getters.projectId,
        id: 0,
        name: '',
        before: '',
        caseType: 1,
        editStatus: 1,
        priority: 2,
        type: 1,
        steps: [{
          id: 0,
          projectId: this.$store.getters.projectId,
          extra1: '',
          extra2: '',
          error: 0
        }]
      })
    },
    // 保存 catalog 对象
    saveCatalog() {
      this.$refs['updateCatalog'].validate((valid) => {
        if (valid) {
          // 保存当前目录下步骤和用例信息
          this.catalogInfo.type = this.type
          this.catalogInfo.projectId = this.$store.getters.projectId
          if (!this.catalogInfo.id || this.catalogInfo.id === 0) { // id = 0，新增
            // 跟目录设置 parentId = 0
            if (!this.catalogInfo.parentId) {
              this.catalogInfo.parentId = 0
            }
            create(this.catalogInfo).then((response) => {
              if (this.type === 1 && !this.readonly) {
                for (const index in this.caseTableData) {
                  this.caseTableData[index]['catalogId'] = response.data.id
                }
                this.catalogInfo.id = response.data.id
                this.caseTableData = this.caseTableData.slice(0, -1) // 删除最后一行无效数据
                saveOrUpdateBatch(this.caseTableData).then((response) => {
                  this.caseTableData = response.data
                }).finally(() => {
                  this.newTableRow()
                })
              }
              this.$emit('create', response.data)
              this.$message({ message: '添加成功!', type: 'success' })
            })
          } else { // 否则修改
            update(this.catalogInfo).then((response) => {
              if (this.type === 1 && !this.readonly) {
                for (const index in this.caseTableData) {
                  this.caseTableData[index]['catalogId'] = this.catalogInfo.id
                }
                this.caseTableData = this.caseTableData.slice(0, -1) // 删除最后一行无效数据
                saveOrUpdateBatch(this.caseTableData).then((response) => {
                  this.caseTableData = response.data
                }).finally(() => {
                  this.newTableRow()
                })
              }
              this.$emit('update', response.data)
              this.$message({ message: '修改成功!', type: 'success' })
            })
          }
        }
      })
    }
  }
}
</script>
